﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Simhopp.Client
{
    /// <summary>
    /// The AttachedProperties class is used to register command bindings from WPF.
    /// </summary>
    static class AttachedProperties
    {
        public static DependencyProperty RegisterCommandBindingsProperty = 
            DependencyProperty.RegisterAttached("RegisterCommandBindings", 
            typeof(CommandBindingCollection), 
            typeof(AttachedProperties),
            new PropertyMetadata(null, OnRegisterCommandBindingChanged));


        /// <summary>
        /// Called when assigning to the RegisterCommandBindings property
        /// </summary>
        /// <param name="element">The invoking element</param>
        /// <param name="value">The commandbindingcollection to register</param>
        public static void SetRegisterCommandBindings(UIElement element, CommandBindingCollection value)
        {
            if (element != null)
                element.SetValue(RegisterCommandBindingsProperty, value);
        }
        
        /// <summary>
        /// Returns the registered commandbindingcollection
        /// </summary>
        /// <param name="element">The invoking element</param>
        /// <returns>The commandbindingcollection</returns>
        public static CommandBindingCollection GetRegisterCommandBindings(UIElement element)
        {
            return (element != null ? (CommandBindingCollection)element.GetValue(RegisterCommandBindingsProperty) : null);
        }

        /// <summary>
        /// Invoked when the dependcyproperty is changed
        /// </summary>
        /// <param name="sender">The object upon which the property is registered</param>
        /// <param name="e">the event arguments</param>
        private static void OnRegisterCommandBindingChanged
        (DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            UIElement element = sender as UIElement;
            if (element != null)
            {
                CommandBindingCollection bindings = e.NewValue as CommandBindingCollection;
                if (bindings != null)
                {
                    element.CommandBindings.AddRange(bindings);
                }
            }
        }
    }
}
